<?php
namespace app\controller\productAvatar;

use app\BaseController;
use app\service\TopviewApiService;
use think\facade\Cache;
use think\facade\Db;

class Resource extends BaseController
{
    protected $apiService;

    public function __construct()
    {
        $this->apiService = new TopviewApiService();
    }

    /**
     * 获取商品数字人列表
     */
    public function avatarList()
    {
        try {
            $pageNo = input('pageNo/d', 1);
            $pageSize = input('pageSize/d', 20);
            $ethnicityIds = input('ethnicityIds', '');
            $gender = input('gender', '');
            $sortingType = input('sortingType', '');
            $categoryIds = input('categoryIds', '');

            // 验证gender参数
            if (!empty($gender) && !in_array($gender, ['male', 'female'])) {
                return json([
                    'code' => 400, 
                    'msg' => 'gender参数只能是male或female',
                    'data' => null
                ]);
            }

            // 验证sortingType参数
            if (!empty($sortingType) && !in_array($sortingType, ['Popularity', 'Newest'])) {
                return json([
                    'code' => 400, 
                    'msg' => 'sortingType参数只能是Popularity或Newest',
                    'data' => null
                ]);
            }

            $data = $this->apiService->getProductAvatarPublicList($pageNo, $pageSize, $ethnicityIds, $gender, $sortingType, $categoryIds);
            
            // 替换图片地址为OSS地址
            if (isset($data['data']) && is_array($data['data'])) {
                $data['data'] = $this->replaceWithOssUrls($data['data']);
            }
            
            return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 将原始图片地址替换为OSS地址
     */
    private function replaceWithOssUrls($avatars)
    {
        if (empty($avatars)) {
            return $avatars;
        }
        
        // 收集所有的avatarId
        $avatarIds = array_column($avatars, 'avatarId');
        
        if (empty($avatarIds)) {
            return $avatars;
        }
        
        // 批量查询OSS地址（只获取迁移成功的）
        $ossUrls = Db::table('product_avatar_resources')
            ->whereIn('avatar_id', $avatarIds)
            ->where('status', 1) // 只获取迁移成功的
            ->where('oss_image_url', '<>', '') // OSS地址不为空
            ->column('oss_image_url', 'avatar_id');
        
        // 替换图片地址（只替换迁移成功的）
        foreach ($avatars as &$avatar) {
            $avatarId = $avatar['avatarId'] ?? '';
            if ($avatarId && isset($ossUrls[$avatarId]) && !empty($ossUrls[$avatarId])) {
                // 确保OSS地址不是原始CloudFront地址
                if (strpos($ossUrls[$avatarId], 'aliyuncs.com') !== false) {
                    $avatar['avatarImagePath'] = $ossUrls[$avatarId];
                }
            }
            // 如果没有找到OSS地址或迁移失败，保持原始地址不变
        }
        
        return $avatars;
    }

    /**
     * 获取商品数字人类目列表
     */
    public function categoryList()
    {
        try {
            // 缓存键
            $cacheKey = 'product_avatar_category_list';
            
            // 尝试从缓存获取数据
            $data = Cache::get($cacheKey);
            if ($data === null) {
                // 缓存不存在，从API获取数据
                $data = $this->apiService->getProductAvatarCategoryList();
                // 设置缓存，有效期1小时
                Cache::set($cacheKey, $data, 3600);
            }

            // 将英文类目名称转换为中文
            $data = $this->translateCategoriesToChinese($data);

            return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 将类目名称翻译为中文
     */
    private function translateCategoriesToChinese($data)
    {
        // 英文到中文的映射表（基于实际接口返回的数据）
        $categoryMapping = [
            '🥫 Vitamins & Supplements' => '🥫 维生素和保健品',
            '🏂 Sports & Outdoor' => '🏂 运动和户外',
            ' 📿 Jewelry' => ' 📿 珠宝',
            '👗 Clothing' => '👗 服装',
            '✒️ Stationery & Office Supplies' => '✒️ 文具和办公用品',
            '⌚ Watches' => '⌚ 手表',
            '📱 App' => '📱 应用',
            '🍽️ Kitchen Accessories' => '🍽️ 厨房配件',
            '🏍️ Cycling Accessories' => '🏍️ 骑行配件',
            '🛠️ Tools' => '🛠️ 工具',
            '🍕 Food ' => '🍕 食品',
            '👩‍🍼 Maternity & Baby Products' => '👩‍🍼 母婴用品',
            '📖 Books' => '📖 图书',
            '💼 Bags & Luggage' => '💼 包包和行李箱',
            '🍷 Drinkware' => '🍷 饮品器具',
            '👟 Footwear' => '👟 鞋类',
            '🍾 Beverages' => '🍾 饮料',
            '🎮 Tech & Electronics' => '🎮 科技和电子产品',
            '🧴 Perfume' => '🧴 香水',
            '💄 Beauty & Personal Care' => '💄 美容和个人护理',
            '💊 Medication' => '💊 药品',
            '🍳Kitchen Appliances' => '🍳厨房电器',
            '🐱 Pets' => '🐱 宠物',
            '🗄️ Large Appliances' => '🗄️ 大型家电',
            '🧹 Cleaning Appliances' => '🧹 清洁电器',
            '😎 Glasses' => '😎 眼镜',
            '👱🏻‍♀️ Wig' => '👱🏻‍♀️ 假发',
            '🛋️ Indoor Furniture' => '🛋️ 室内家具',
            '🛵 Electric Bike' => '🛵 电动自行车',
            '🧺 Outdoor Furniture' => '🧺 户外家具',
            '👒 Hat' => '👒 帽子',
            ' 🏀 Sports Equipment' => ' 🏀 运动器材',
            'General' => '通用'
        ];

        // 如果数据是数组，遍历处理
        if (is_array($data)) {
            foreach ($data as &$item) {
                if (isset($item['categoryName']) && is_string($item['categoryName'])) {
                    $originalName = $item['categoryName'];
                    $item['categoryName'] = $categoryMapping[$originalName] ?? $originalName;
                    // 保留原始英文名称
                    $item['categoryNameEn'] = $originalName;
                }
            }
        }

        return $data;
    }
} 